/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.discussions.server.replay;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.gadglet.core.BizletRequestHandler;
import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.core.GadgletResponse;
import com.gadglet.core.GadgletResponse.ContentRecord;
import com.gadglet.core.RequestException;
import com.gadglet.data.DomainUser;
import com.gadglet.data.DomainUserUtils;
import com.gadglet.data.utils.ContentItemHelper;
import com.gadglet.data.utils.PMF;
import com.gadglet.gadgets.discussions.server.DiscussionsList;
import com.gadglet.gadgets.discussions.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqErrorTypes;

public class RequestHandler extends BizletRequestHandler {
	Logger log = Logger.getLogger(this.getClass().getName());

	private final ContentItemHelper helper = new ContentItemHelper();

	/**
	 * Delete Personal note
	 * */
	@Override
	public void doDelete(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {
		throw new RequestException(ReqErrorTypes.UNRECOGNIZED_ACTION);
	}

	@Override
	public void doAdd(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {

		String replayMsg = null;
		String replayTo = null;
		String replayOrder = null;
		DiscussionsList discussion = null;

		if (request.getParameter(Params.DICUSSION_REPLY.getParamName()) == null
				|| request.getParameter(Params.DICUSSION_REPLY.getParamName())
						.isEmpty())
			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);

		if (request.getParameter(Params.DISCUSSION_PARENT_ID.getParamName()) == null
				|| request.getParameter(
						Params.DISCUSSION_PARENT_ID.getParamName()).isEmpty())
			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);

		replayMsg = request
				.getParameter(Params.DICUSSION_REPLY.getParamName());
		replayTo = request.getParameter(Params.DISCUSSION_PARENT_ID
				.getParamName());

		Replys newReplay = new Replys(request, replayMsg, replayTo);

		PersistenceManager pm = PMF.get().getPersistenceManager();

		discussion = (DiscussionsList) helper.getSingleItemByKeyForAction(pm,
				request, DiscussionsList.class);

		if (discussion == null)
			throw new RequestException(ReqErrorTypes.ITEM_NOT_FOUND);

		List<Replys> replays = discussion.getReply();

		replayOrder = calcOrder(discussion, replayTo);

		newReplay.setReplyOrder(replayOrder);

		replays.add(newReplay);

		pm.makePersistent(discussion);

		pm.close();

	}

	@Override
	public void doUpdate(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {
		throw new RequestException(ReqErrorTypes.UNRECOGNIZED_ACTION);

	}

	@Override
	public void doView(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {

		DiscussionsList discussion = null;

		List<Replys> replays = null;

		PersistenceManager pm = null;
		;
		try {
			pm = PMF.get().getPersistenceManager();

			discussion = (DiscussionsList) helper.getSingleItemByKeyForAction(
					pm, request, DiscussionsList.class);

			if (discussion == null)
				throw new RequestException(ReqErrorTypes.ITEM_NOT_FOUND);

			if (discussion.getReply() != null) {
				replays = discussion.getReply();
				for (Replys replay : replays);

			}
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			throw e;
		} catch (Exception e) {
			log.warning(e.getMessage());
			throw new RequestException(ReqErrorTypes.REQUEST_FAILED);
		} finally {
			pm.close();
		}

		ContentRecord item = response.newItem();

		SimpleDateFormat df = new SimpleDateFormat("MMM/dd/yy hh:mm");
		String formatedDate = null;

		item.addItemKeyField(discussion.getContentItemKey());
		item.addItemField(Params.DISCUSSION_TEXT.getParamName(),
				discussion.getDiscussion());

		formatedDate = df.format(discussion.getCreation());

		if (formatedDate != null)
			item.addItemField(Params.DISCUSSION_MSD_DATE.getParamName(),
					formatedDate);
		else
			item.addItemField(Params.DISCUSSION_MSD_DATE.getParamName(), "");

		item.addItemField(Params.DISCUSSION_LEVEL.getParamName(), "0");

		item.setContentName(Params.DISCUSSION_TEXT.getParamName());

		DomainUser writer = DomainUserUtils.getDomainUserByUniqueId(discussion
				.getOwnerId(), request.getCurrentDomainUser().getAccount());

		item.addItemField(ProfileFields.PROFILE_NICKNAME.getParamName(),
				writer.getNickName());
		item.addItemField(ProfileFields.PROFILE_TITLE.getParamName(),
				writer.getTitle());

		if (writer.getPhotoUrl() != null && writer.getPhotoUrl().length() > 0)
			item.addItemField(
					ProfileFields.PROFILE_THUMBNAILURL.getParamName(),
					writer.getPhotoUrl());

		item.setGadgetPermissions(discussion.isUserEdit(request),
				discussion.isOwnedByMe(request),
				discussion.isOwnedByMe(request));

		if (replays != null) {

			for (Replys replay : replays) {
				int level = 0;

				item = response.newItem();
				item.addItemKeyField(replay.getId());
				item.addItemField(Params.DISCUSSION_TEXT.getParamName(),
						replay.getReply());

				formatedDate = df.format(replay.getCdate());

				if (formatedDate != null)
					item.addItemField(
							Params.DISCUSSION_MSD_DATE.getParamName(),
							formatedDate);
				else
					item.addItemField(
							Params.DISCUSSION_MSD_DATE.getParamName(), "");

				if (replay.getReplyOrder() != null)
					level = replay.getReplyOrder().split("\\*").length - 1;
				// this will be used to create UI message indentation
				item.addItemField(Params.DISCUSSION_LEVEL.getParamName(),
						new Integer(level).toString());

				item.setContentName(Params.DICUSSION_REPLY.getParamName());

				writer = DomainUserUtils.getDomainUserByUniqueId(replay
						.getUserName(), request.getCurrentDomainUser()
						.getAccount());

				item.addItemField(
						ProfileFields.PROFILE_NICKNAME.getParamName(),
						writer.getNickName());
				item.addItemField(ProfileFields.PROFILE_TITLE.getParamName(),
						writer.getTitle());

				if (writer.getPhotoUrl() != null
						&& writer.getPhotoUrl().length() > 0)
					item.addItemField(
							ProfileFields.PROFILE_THUMBNAILURL.getParamName(),
							writer.getPhotoUrl());

				item.setGadgetPermissions(discussion.isUserEdit(request),
						false, false);

			}
		}

	}

	private String calcOrder(DiscussionsList discussion, String replayTo) {
		String order = null;
		final String delimiter = "*";
		List<Replys> replays = discussion.getReply();
		int id = 1;
		boolean orderExists = true;
		String ParentReplayOrder = "";
		String leadingZeros = "00";

		// not direct parent of the root
		if (!replayTo.equals(discussion.getContentItemKey())) {
			// search for parent
			for (Replys replay : replays)
				if (replay.getId().equals(replayTo))// save the orderby +
													// delimiter
					ParentReplayOrder = replay.getReplyOrder() + delimiter;
		}

		if (replays == null)
			return leadingZeros + id;

		// look for the next
		while (orderExists && id < 1000) {
			orderExists = false;

			if (id < 100 && id > 9)
				leadingZeros = "0";

			for (Replys replay : replays)
				if (replay.getReplyOrder().equals(
						ParentReplayOrder + leadingZeros + id))
					orderExists = true;

			order = ParentReplayOrder + leadingZeros + id;

			id++;
		}

		return order;
	}

}
